package top.ucat.x.system.service.management;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import top.ucat.box.starter.mybatis.plus.base.service.BaseCrudServiceImpl;
import top.ucat.x.system.dao.api.SysUserDao;
import top.ucat.x.system.entity.SysUser;
import top.ucat.x.system.entity.beans.UserInfoDto;

import java.util.Set;

/**
 * @Auther: Jun
 * @Date: 2020/4/3 13:31
 * @Description:
 */
@Service
public class SysUserServiceImpl extends BaseCrudServiceImpl<SysUser> implements SysUserService {

    @Autowired
    private SysUserDao sysUserDao;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private SysRolePermissionService sysRolePermissionService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Override
    public SysUser add(SysUser sysUser) {
        sysUser.setPassword(bCryptPasswordEncoder.encode(sysUser.getPassword()));
        return super.add(sysUser);
    }

    @Override
    public SysUser update(SysUser sysUser) {
        return super.update(sysUser);
    }

    @Override
    public SysUser getUserByUserCode(String userCode) {
        LambdaQueryWrapper<SysUser> wrapper = sysUserDao.getWrapper().lambda()
                .eq(SysUser::getUserCode, userCode);
        SysUser user = sysUserDao.getOne(wrapper);
        return user;
    }

    @Override
    public UserInfoDto getUserInfoDto(String userId) {

        SysUser sysUser = this.queryById(userId);
        UserInfoDto userInfoDto = UserInfoDto.builder()
                .userInfo(sysUser)
                .admin(sysUser.isAdmin())
                .permission(sysRolePermissionService.getUserPermissionCodes(userId))
                .roles("")
                .build();
        Set<String> userRoleSigns = sysUserRoleService.getUserRoleSigns(userId);
        if (!userRoleSigns.isEmpty()) {
            String roles = StringUtils.join(userRoleSigns, ",");
            userInfoDto.setRoles(roles);
        }
        return userInfoDto;
    }
}
